package net.spatula.tally_ho.service;

/* Copyright 2006 Nicklas R Johnson
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import net.spatula.tally_ho.model.Section;
import net.spatula.tally_ho.service.beans.SectionBean;

public class SectionService {

    private static SectionService instance = null;

    private SectionService() {

    }

    public static synchronized SectionService getInstance() {
        if (instance == null) {
            instance = new SectionService();
        }
        return instance;
    }

    @SuppressWarnings("unchecked")
    public List<SectionBean> getSections(EntityManager em) {
        Query q = em.createQuery("SELECT s FROM Section s ORDER BY s.sequence");
        List<Section> sectionList = q.getResultList();

        List<SectionBean> sections = new ArrayList<SectionBean>(sectionList.size());
        for (Section section : sectionList) {
            sections.add(getSectionBeanFromSection(section));
        }

        return sections;
    }

    public Section getSectionById(EntityManager em, long id) {
        Query q = em.createQuery("SELECT s from Section s WHERE s.objectId = ?1");
        q.setParameter(1, id);
        Section section = (Section)q.getSingleResult();
        return section;
    }
    
    SectionBean getSectionBeanFromSection(Section section) {
        return new SectionBean(section.getObjectId(), section.getName(), section.getDescription());
    }

}
